<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="24">
          <a-form-item label="作品方向（Channel）" v-bind="validateInfos.workDirection">
            <j-dict-select-tag
              v-model:value="formData.workDirection"
              dictCode="work_direction"
              placeholder="请选择作品方向"
              :disabled="disabled"
              :showChooseOption="false"
              mode="multiple"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="分类名（Genre）" v-bind="validateInfos.catId">
            <j-dict-select-tag
              v-model:value="formData.catId"
              dictCode="book_category"
              placeholder="请选择分类名"
              :disabled="disabled"
              :showChooseOption="false"
              mode="multiple"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="小说封面" v-bind="validateInfos.picUrl">
            <div style="height: 112px">
              <j-image-upload v-model:value="formData.picUrl" :disabled="disabled" :fileSize="40" @change="upPic" />
            </div>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="小说名" v-bind="validateInfos.bookName">
            <a-input v-model:value="formData.bookName" placeholder="请输入" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <!-- <a-col :span="24">
          <a-form-item label="作者id" v-bind="validateInfos.authorId">
            <a-input v-model:value="formData.authorId" placeholder="请输入" style="width: 100%" :disabled="disabled" />
          </a-form-item>
        </a-col> -->
        <a-col :span="24">
          <a-form-item label="作者名" v-bind="validateInfos.authorName">
            <a-input v-model:value="formData.authorName" placeholder="请输入" style="width: 100%" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="书籍描述" v-bind="validateInfos.bookDesc">
            <a-input v-model:value="formData.bookDesc" placeholder="请输入" style="width: 100%" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="评分" v-bind="validateInfos.score">
            <a-input-number
              v-model:value="formData.score"
              placeholder="请输入"
              :max="10"
              :step="0.1"
              :precision="1"
              style="width: 100%"
              :disabled="disabled"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="书籍状态" v-bind="validateInfos.bookStatus">
            <a-select v-model:value="formData.bookStatus" placeholder="请选择" allowClear :disabled="disabled">
              <a-select-option :value="0">Ongoing</a-select-option>
              <a-select-option :value="1">Complete</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="是否收费" v-bind="validateInfos.isVip">
            <j-switch v-model:value="formData.isVip" :disabled="disabled" :options="[1, 0]" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="状态" v-bind="validateInfos.status">
            <a-select v-model:value="formData.status" placeholder="请选择" allowClear :disabled="disabled">
              <a-select-option :value="0">入库</a-select-option>
              <a-select-option :value="1">上架</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="语言" v-bind="validateInfos.language">
            <j-dict-select-tag
              v-model:value="formData.language"
              dictCode="language"
              :showChooseOption="false"
              placeholder="请选择语言"
              :disabled="disabled"
              @update:key="languageUpdate"
              ref="languageSelectRef"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="平台" v-bind="validateInfos.platform" class="platform-select">
            <j-dict-select-tag
              v-model:value="formData.platform"
              dictCode="platform"
              ref="dictSelectRef"
              placeholder="请选择平台"
              :disabled="disabled"
              :showChooseOption="false"
              mode="multiple"
            />
            <a-button type="primary" @click="chooseAllPlateform">全选</a-button>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="是否自动采集" v-bind="validateInfos.isAutoCollection">
            <j-switch v-model:value="formData.isAutoCollection" :disabled="disabled" :options="[1, 0]" @change="isAutoCollectionChange" />
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="formData.isAutoCollection">
          <a-form-item label="采集器" v-bind="validateInfos.collector">
            <a-select
              v-model:value="formData.collector"
              placeholder="请选择"
              :disabled="disabled"
              :showSearch="true"
              :optionFilterProp="'label'"
              :options="collectionList"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="formData.isAutoCollection">
          <a-form-item label="采集地址" v-bind="validateInfos.collectionUrl">
            <a-input v-model:value="formData.collectionUrl" placeholder="请输入" style="width: 100%" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="备注" v-bind="validateInfos.remark">
            <a-textarea v-model:value="formData.remark" placeholder="请输入" auto-size style="width: 100%" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="是否签约" v-bind="validateInfos.isContract">
            <a-select v-model:value="formData.isContract" placeholder="请选择是否签约" :disabled="disabled">
              <a-select-option :value="true">是</a-select-option>
              <a-select-option :value="false">否</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JSwitch from '/@/components/Form/src/jeecg/components/JSwitch.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate } from '../BookIndex.api';
  import { Form } from 'ant-design-vue';
  import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
  import JDictSelectTag from '@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => {} },
    formBpm: { type: Boolean, default: true },
  });
  const checked = ref<boolean>(false);
  const formRef = ref();
  const languageSelectRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    workDirection: [],
    catId: [],
    picUrl: '',
    bookName: '',
    // authorId: '',
    authorName: '',
    bookDesc: '',
    score: 8.5,
    bookStatus: 0,
    status: 1,
    language: 'EN',
    isAutoCollection: 1,
    collectionUrl: '',
    collector: '',
    isVip: 0,
    platform: ['0', '1'],
    remark: '',
    isContract: false,
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = {
    // bookId: [{ required: true, message: '请输入小说ID!'},],
    // indexNum: [{ required: true, message: '请输入目录号!'},],
    // storageType: [{ required: true, message: '请输入存储方式!'},],
  };
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules);

  // 表单禁用
  const disabled = computed(() => {
    if (props.formBpm === true) {
      if (props.formData.disabled === false) {
        return false;
      } else {
        return true;
      }
    }
    return props.formDisabled;
  });

  const collectionList = ref();
  const dictSelectRef = ref();

  // 采集器下拉
  async function getCollectionList() {
    const data = await defHttp.get({ url: '/novel/book/collectionList' });
    let arr = [];
    data.forEach((item) => {
      arr.push({
        label: item.text,
        value: item.value,
      });
    });
    collectionList.value = arr;
  }

  getCollectionList();

  /**
   * 新增
   */
  function add() {
    formData.picUrl = '';
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    let data = JSON.parse(JSON.stringify(record));
    data.workDirection = data.workDirection.split(',');
    data.catId = data.catId.split(',');
    data.platform = data.platform.split(',');
    if (data.id) {
      languageUpdate(data.language);
    }
    nextTick(() => {
      resetFields();
      //赋值
      Object.assign(formData, data);
    });
  }

  function isAutoCollectionChange(val) {
    if (!val) {
      formData.collector = '';
      formData.collectionUrl = '';
    }
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    await validate();
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = JSON.parse(JSON.stringify(formData));
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    model.language = languageSelectRef.value.getLable(model.language);
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  async function upPic(val) {
    formData.picUrl = val;
  }
  const languageLabel = ref();
  function languageUpdate(val) {
    languageLabel.value = val;
  }
  function chooseAllPlateform() {
    let arr = [];
    dictSelectRef.value.dictOptions.forEach((item) => {
      arr.push(item.value);
    });
    formData.platform = arr;
  }

  defineExpose({
    add,
    edit,
    submitForm,
    formData,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    min-height: 500px !important;
    overflow-y: auto;
    padding: 24px 24px 24px 24px;
  }
  .platform-select {
    :deep .ant-form-item-control-input-content {
      display: flex;
    }
  }
</style>
